<template>
    <div class="tree-container">
        <div class="header">
            <!-- <div class="title">组织机构管理</div> -->
            <div class="left">
                <el-input placeholder="请输入组织机构" v-model="orgName" style="width: 100%" size="small" clearable
                    @clear="onClear">
                    <el-button slot="append" :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
                        @click="searchClick">
                    </el-button>
                </el-input>
            </div>
        </div>
        <div :class="['middle', first ? 'middle1' : '']">
            <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" ref="refTree" v-if="isTree"
                node-key="id" :load="loadNode" lazy highlight-current :current-node-key="defaultCheckedKeys">
                <div class="custom-tree-node" slot-scope="{ node, data }" @mouseenter="slideIn(data)"
                    @mouseleave="slideAway(data)">
                    <div>
                        <i class="iconfont qiye" v-if="node.level == '1'"></i>
                        <i class="iconfont zuzhi" v-else></i>
                        {{ node.label }}
                    </div>
                </div>
            </el-tree>
        </div>
    </div>
</template>

<script>
import { reqOrgList,  } from "@api/api.js";
import { mapState } from "vuex";
import { transTree } from "@utils/trans-tree";

export default {
    components: {},
    mixins: [],
    data() {
        return {
            dataTree: [],
            page: 1,
            limit: 30,
            total: 0,
            orgName: "",
            defaultProps: {
                children: "children",
                label: "orgName",
                isLeaf: "hasChildren",
                id: "id",
            },
            first: true, //第一次加载，点击后消除
            loadingSearch: false,
            firstInfo: {}, //默认第一条信息
            editOrgInfo: {}, //修改一条组织机构信息
            detailOrgInfo: {}, //详情
            flagtree: false,
            data: [],
            isTree: true,
            currentData: "",
            currentNode: "",
            defaultCheckedKeys: "", // 选择节点后默认展示
            defaultCheckedKeys_copy: "",
        };
    },
    computed: {
        ...mapState(["user", "spacesManage"]),
    },
    mounted() {

    },
    created() {
        if (this.spacesManage.organizationInfo.orgId != "") {
            this.first = false;
            this.defaultCheckedKeys = this.spacesManage.organizationInfo.orgId;
            this.$nextTick(() => {
                this.$refs.refTree.setCurrentKey(this.spacesManage.organizationInfo.orgId);//通过 key 设置某个节点的当前选中状态
            })
        } else {
            this.first = true;
        }
        // this.getDataList2()
    },
    inject: ["reload"], //局部刷新
    methods: {
        // 刷新
        updateOrg() {
            this.isTree = false;
            setTimeout(() => {
                this.isTree = true;
            }, 0);
        },
        // 获取列表
        // async getDataList2() {
        //     let params = {
        //         tenantId: this.user.tenantId,
        //         userId: this.user.userId,
        //         roleName: this.user.roleName,
        //         orgName: this.orgName,
        //     };
        //     let res = await reqOrgList(params);
        //     if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
        //     let { rows } = res.data;
        //     let data = {
        //         orgId: rows[0].id,
        //         orgName: rows[0].orgName,
        //         role: rows[0].role,
        //     };
        //     this.$store.commit("saveOrganizationInfo", data); //保存信息，使页面刷新信息还存在
        //     this.$emit("toggleOrgId", data);
        // },
        // 获取列表
        async getDataList() {
            let params = {
                tenantId: this.user.tenantId,
                userId: this.user.userId,
                roleName: this.user.roleName,
                orgName: this.orgName,
            };
            let res = await reqOrgList(params);
            // console.log(res, "res222");
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            let { rows, total } = res.data;
            this.dataList = transTree(rows);//返回全部数据
        },

        // 树节点懒加载
        async loadNode(node, resolve) {
            // console.log(node, "node222");
            if (node.level == 0) {
                // 如果是一级单位
                let params = {
                    tenantId: this.user.tenantId,
                    userId: this.user.userId,
                    roleName: this.user.roleName,
                    orgName: this.orgName,
                };
                let res = await reqOrgList(params);
                console.log(res, "res222");

                if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                let { rows, total } = res.data;
                rows.forEach((item) => {
                    if (item.hasChildren === 1) {
                        item.hasChildren = false;
                    } else {
                        item.hasChildren = true;
                    }
                });
                if (!this.defaultCheckedKeys_copy) {
                    if (rows.length > 0) {
                        let data = {
                            orgId: rows[0].id,
                            orgName: rows[0].orgName,
                            role: rows[0].role,
                        };
                        // console.log(this.spacesManage.organizationInfo);
                        if (!this.spacesManage.organizationInfo.orgId) {
                            // console.log(this.spacesManage.organizationInfo.orgId);
                            // 第一次登录进来
                            this.first = true;
                            this.$store.commit("saveOrganizationInfo", data); //保存信息，使页面刷新信息还存在
                            this.$emit("toggleOrgId", data);
                            // this.defaultCheckedKeys = data.orgId;
                            // this.$nextTick(()=>{
                            //     this.$refs.refTree.setCurrentKey(data.orgId);//通过 key 设置某个节点的当前选中状态
                            // })
                        } else {
                            // this.first = false;
                            // this.defaultCheckedKeys = this.spacesManage.organizationInfo.orgId;
                            // this.$refs.refTree.setCurrentKey(this.spacesManage.organizationInfo.orgId);
                        }
                    } else {
                        // 组织机构筛选为空时
                        let data = {
                            orgId: "",
                            orgName: "",
                            role: 2,
                        };
                        console.log(222222);
                        this.$store.commit("saveOrganizationInfo", data); //保存信息，使页面刷新信息还存在
                        this.$emit("toggleOrgId", data);
                    }
                }
                return resolve(rows);
            } else {
                // 否则是下级单位
                let params = {
                    tenantId: this.user.tenantId,
                    userId: this.user.userId,
                    roleName: this.user.roleName,
                    orgName: this.orgName,
                    parentId: node.data.id,
                };
                let res = await reqOrgList(params);
                if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                let rows = res.data.rows;
                rows.forEach((item) => {
                    if (item.hasChildren === 1) {
                        item.hasChildren = false;
                    } else {
                        item.hasChildren = true;
                    }
                });
                return resolve(rows);
            }
        },
        // 清空输入框
        async onClear() {
            if (this.defaultCheckedKeys_copy && !this.defaultCheckedKeys) {
                this.defaultCheckedKeys = this.defaultCheckedKeys_copy;
            }
            this.loadingSearch = true;
            await this.updateOrg();
            this.loadingSearch = false;
        },
        getInitDataList() {
            this.page = 1;
            this.limit = 30;
            this.getDataList();
        },
        handleSizeChange(val) {
            this.limit = val;
            this.getDataList();
        },
        handleCurrentChange(val) {
            this.page = val;
            this.getDataList();
        },
        // 点击一条
        handleNodeClick(data, node) {
            this.currentData = data;
            this.currentNode = node;
            this.$refs.refTree.setCurrentKey(data.id);
            this.defaultCheckedKeys = data.id;
            let params = {
                orgId: data.id,
                orgName: data.orgName,
                role: data.role,
            };
            this.$store.commit("saveOrganizationInfo", params); //保存信息，使页面刷新信息还存在
            this.$emit("toggleOrgId", params);
            this.first = false;
            this.reload(); //局部刷新
        },
        // 查询组织机构
        async searchClick() {
            this.loadingSearch = true;
            this.defaultCheckedKeys_copy = JSON.parse(
                JSON.stringify(this.defaultCheckedKeys)
            );
            await this.updateOrg();
            if (this.orgName != "") {
                this.defaultCheckedKeys = "";
            }
            this.loadingSearch = false;
        },
        // 滑动进去一条
        slideIn(data) {
            this.$set(data, "showCtrls", true);
        },
        slideAway(data) {
            // console.log(data);
            this.$set(data, "showCtrls", false);
        },
    },
};
</script>

<style scoped lang="less">
.tree-container {
    width: 100%;
    height: 400px;
    overflow-y: auto;

    .header {
        position: relative;
        height: 65px;
        padding: 0 20px;
        border-bottom: 1px solid @primaryBorderColor;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .title {
            width: 25%;
            font-size: 20px;
            color: @primaryThemeTxtColor;
            font-weight: 600;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        .el-icon-search {
            //   color: @primaryBorderColor;
            //   font-size: 20px;
        }

        .left {
            width: 100%;
        }

        .right {
            width: 75%;
            display: flex;
            justify-content: flex-end;
            //   justify-content: space-between;
        }
    }

    .middle {
        height: calc(100% - 65px);
        overflow: hidden;
        overflow-y: scroll;

        .custom-tree-node {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: relative;
            padding-left: 0.5%;
            box-sizing: border-box;

            .guanliyuan_guanliyuanliebiao {
                position: absolute;
                left: -2.5%;
                font-size: 12px;
            }

            .tree-node_ctrls {
                position: absolute;
                right: 0;
                width: 30%;
                text-align: right;
                padding-right: 10px;
                // background-color: pink;

                i {
                    color: #aaa;
                    font-size: 20px;
                    margin-right: 10px;

                    &:hover {
                        color: #fff;
                    }
                }
            }
        }

        ::v-deep .el-tree {
            height: 100%;
            font-size: 14px;
            background: @primaryHeaderBgcolor;
            box-sizing: border-box;
            padding: 12px 10px;
            color: @primaryThemeTxtColor;
            overflow: hidden;
            overflow-y: scroll;
        }

        ::v-deep .el-tree-node__content {

            // padding: 5px 0 !important;
            &:hover {
                background: @paginationBgcolor !important;
                border-radius: 4px;
            }
        }

        ::v-deep .el-tree-node.is-current.is-focusable>.el-tree-node__content {
            background-color: #7367f0 !important;
            border-radius: 4px;
        }

        ::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
            padding: 5px 0;
        }

        // 解决点击白底问题
        ::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
            // background-color: @primaryTree;
            border-radius: 4px;
        }

        ::v-deep .is-current>.el-tree-node__content>.el-tree-node__label {
            color: #f0f0f0;
        }

        .el-icon-more {
            color: @primaryThemeTxtColor;
            font-size: 15px;
            margin-right: 10px;
        }

        // 组织机构更多
        ::v-deep .is-current>.el-tree-node__content>.custom-tree-node>.el-dropdown .el-icon-more {
            color: #f0f0f0;
        }
    }

    .middle1 {
        // ::v-deep .el-tree .el-tree-node.is-focusable:first-child {
        //   background-color: #7367f0 !important;
        //   border-radius: 4px;
        //   .el-tree-node__content {
        //     color: #f6f6f6;
        //   }

        //   .el-tree-node__content {
        //     padding: 5px 0 !important;
        //     &:hover {
        //       background: #7367f0 !important;
        //       border-radius: 4px;
        //     }
        //   }
        // }

        // 解决点击白底问题
        ::v-deep .el-tree>.el-tree-node:first-of-type>.el-tree-node__content {
            background-color: #7367f0 !important;
            color: #f0f0f0;
        }

        // 组织机构更多
        ::v-deep .el-tree>.el-tree-node:first-of-type>.el-tree-node__content .el-icon-more {
            color: #f0f0f0;
        }
    }
}

// 解决收起后白色背景问题
::v-deep .el-tree-node.is-expanded>.el-tree-node__content {
    background-color: transparent;
}

// 解决展开后白色背景问题
::v-deep .el-tree-node.is-focusable>.el-tree-node__content {
    background-color: transparent;
}

// input后面的查询按钮
::v-deep .el-input-group__append {
    color: #fff;
    border: none;
    background-color: #7367f0;
}
</style>
